package com.zw.netty.Server.Handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zw.netty.Server.util.HandUtil;
import com.zw.common.ChatConstants;
import com.zw.sys.Service.DeviceDataService;
import com.zw.sys.Service.DeviceService;
import com.zw.sys.entity.Device;
import com.zw.sys.entity.DeviceData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.springframework.messaging.simp.SimpMessagingTemplate;


import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-04-26 13:53
 */

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    private final ZwChannelGroup group;

    private DeviceDataService deviceDataService;

    private DeviceService deviceService;


    private  SimpMessagingTemplate template;
    public ServerHandler(ZwChannelGroup group,SimpMessagingTemplate template,Map<String,Object> map){
            this.group=group;
            this.template=template;
            this.deviceDataService= (DeviceDataService) map.get("deviceDataService");
            this.deviceService= (DeviceService) map.get("deviceService");
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println(s);
        if(s.contains("@G")){
            String[] strings=s.split(",");
            Optional<Device> device=HandUtil.CreateDevice(s);
            Integer key=Integer.valueOf(strings[2].trim());
            switch (key){
                case 1:ctx.writeAndFlush(HandUtil.joinParam("38,"+ HandUtil.GetDateString(new Date(),"yyyyMMddHHmmss")));break;//时间同步报文
                case 2:break;//开机通告
                case 6:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//轨迹报文GPS
                case 9:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//离手判断心率为0
                case 13:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setStepNumber(Integer.valueOf(strings[6]));break;//计步周期上传
                case 14:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setHeartRate(Integer.valueOf(strings[6]));break;//心率周期上传
                case 43:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));break;//轨迹报文基站wif定位
                case 44:ctx.writeAndFlush(HandUtil.joinParam("21"));break;//心跳报文
                case 99:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setHeartRate(Integer.valueOf(strings[6]));break;//心率异常
                case 110:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setPressure(strings[6]+"/"+strings[7]);break;//血压正常
                case 113:deviceDataService.insert(new DeviceData(device.get().getSerial(),new Date(),device.get().getCurrentCmd(),key));device.get().setPressure(strings[6]+"/"+strings[7]);break;//血压异常
            }
            if(group.find(ctx.channel().id())==null){
                group.add(ctx.channel(),device.get().getSerial());

            }
            device.get().setChannelId(ctx.channel().id().asShortText());
            if(key.intValue()!=44&&key.intValue()>2){
                Device device1= ObjectUtil.clone(device.get());
                EntityWrapper<Device> ew=new EntityWrapper<>();
                ew.where("serial={0}",device.get().getSerial());
                device1.setCurrentCmd(null);
                deviceService.update(device1,ew);
            }
            template.convertAndSend("/topic/userList",device.get());
        }
    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有设备接入："+ctx.channel().id().asShortText());
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            template.convertAndSend("/topic/userList", ChatConstants.onlines);
            System.out.println("客户端："+ctx.channel()+"断开连接");
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }


}
